package org.zh.home.dao.impl;

import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import org.zh.home.dao.BaseDao;
import org.zh.home.dao.IResourceDao;
import org.zh.home.entity.Resource;
import org.zh.home.model.Pager;
import org.zh.home.model.Param;
import org.zh.home.model.Query;
import org.zh.home.utils.QueryUtils;

@Repository
@SuppressWarnings("unchecked")
public class ResourceDao extends BaseDao<Resource> implements IResourceDao{

	@Override
	public List<Resource> listResourceByUser(int userId) {
		String sql = "select r.* from sdf_resource r RIGHT JOIN (select rr.resource_id from sdf_role_resource rr where rr.role_id IN (select ugr.role_id from sdf_user_group_role ugr where ugr.user_id = "+userId+")) r1 on (r.id = r1.resource_id)";
		return super.listBySql(sql, Resource.class, true);
	}

	@Override
	public List<Resource> listResourceByRole(int roleId) {
		String sql = "select r.* from sdf_resource r RIGHT JOIN (select rr.resource_id from sdf_role_resource rr where rr.role_id IN (select ugr.role_id from sdf_user_group_role ugr where ugr.role_id = "+roleId+")) r1 on (r.id = r1.resource_id)";
		return super.listBySql(sql, Resource.class, true);
	}

	@Override
	public List<Integer> listResourceIdsByUser(int userId) {
		String sql = "select rr.resource_id from sdf_role_resource rr where rr.role_id IN (select ugr.role_id from sdf_user_group_role ugr where ugr.user_id = "+userId+")";
		Session session = super.getSession();
		SQLQuery query = session.createSQLQuery(sql);
		return query.list();
	}

	@Override
	public List<Integer> listResourceIdsByRole(int roleId) {
		String sql = "select rr.resource_id from sdf_role_resource rr where rr.role_id IN (select ugr.role_id from sdf_user_group_role ugr where ugr.role_id = "+roleId+")";
		Session session = super.getSession();
		SQLQuery query = session.createSQLQuery(sql);
		return query.list();
	}

	@Override
	public Pager<Resource> findResource(List<Query> model) {
		Param param = QueryUtils.generateHQLBase("from Resource","r", model);
		return super.find(param.getQuery(), param.getValues().toArray());
	}

}
